package cn.rengy.tpa.wxmp.component.oauth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.oauth.protocol.get_access_token.GetAccessTokenResponse;
import cn.rengy.tpa.wxmp.token.AccessToken;

/**
 * 代公众号发起网页授权
 * <p>
 * 参考<a href=
 * "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=21f49a61199315261accdb409a64e60f22cb2eeb&lang=zh_CN">开发文档</a>
 * </p>
 */
public class ComponentAuthManager {

	private static Logger logger = LoggerFactory.getLogger(ComponentAuthManager.class);

	/* 生成OAuth重定向URI（用户同意授权，获取code） */
	private static final String OAUTH2_AUTHORIZE = "https://open.weixin.qq.com/connect/oauth2/authorize?";
	/* 通过code换取网页授权access_token */
	private static final String OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/component/access_token?";
	/* 刷新access_token（如果需要） */
	private static final String OAUTH2_REFRESH_TOKEN = "";


	/**
	 * 
	 * @param appid
	 * @param redirectURI
	 * @param scope
	 * @param state
	 * @param component_appid
	 * @return
	 */
	public static String generateRedirectURI(String appid,String redirectURI, String scope, String state,String component_appid) {
		StringBuffer url = new StringBuffer();
		url.append(OAUTH2_AUTHORIZE);
		url.append("appid=").append(appid);
		url.append("&redirect_uri=").append(urlEncode(redirectURI));
		url.append("&response_type=code");
		url.append("&scope=").append(scope);
		url.append("&state=").append(urlEncode(state));
		url.append("&component_appid=").append(component_appid);
		url.append("#wechat_redirect");
		return url.toString();
	}

	/**
	 * 通过code换取access_token
	 * @param appid
	 * @param code
	 * @param component_appid
	 * @param accessToken
	 * @return
	 * @throws WeChatException
	 */
	public static GetAccessTokenResponse getAccessToken(String appid,String code,String component_appid,AccessToken accessToken) throws WeChatException {
		StringBuffer url = new StringBuffer(OAUTH2_ACCESS_TOKEN);
		url.append("appid=").append(appid);
		url.append("&code=").append(code);
		url.append("&grant_type=authorization_code");
		url.append("&component_appid=").append(component_appid)
		.append("&component_access_token=");
		String postUrl=url.toString();
		for(int i=0;i<2;i++){
			String resultStr = HttpUtils.post(postUrl+accessToken.token());
			JSONObject jsonObject = JSONObject.parseObject(resultStr);
			int errCode =jsonObject.getIntValue("errcode");
			if(errCode==0){
				return JSONObject.parseObject(resultStr, GetAccessTokenResponse.class);
			}else if(errCode==40001){
				accessToken.refresh();
			}else{
				String errmsg=jsonObject.getString("errmsg");
				throw new WeChatException(errCode,errmsg);
			}
		}
		return null;
	}


	/**
	 * 使用UTF-8进行URL编码
	 *
	 * @param str
	 * @return
	 */
	private static String urlEncode(String str) {
		String result = null;
		try {
			result = URLEncoder.encode(str, Consts.UTF_8.name());
		} catch (UnsupportedEncodingException e) {
			// never throws
		}
		return result;
	}

	

	

}
